{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Step 1: Create $100M portfolio and upload positions to GS Financial Cloud"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import datetime as dt\n",
    "import warnings\n",
    "import pandas as pd\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import seaborn as sns\n",
    "from IPython.display import display\n",
    "\n",
    "from gs_quant.markets.portfolio import Portfolio\n",
    "from gs_quant.markets.portfolio_manager import PortfolioManager\n",
    "from gs_quant.markets.position_set import PositionSet\n",
    "from gs_quant.markets.report import FactorRiskReport\n",
    "from gs_quant.session import GsSession\n",
    "from gs_quant.target.reports import PositionSourceType, ReportType\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "GsSession.use()\n",
    "\n",
    "\n",
    "portfolio = Portfolio(name='My New Portfolio')\n",
    "portfolio.save()\n",
    "print(f\"'{portfolio.name}' Portfolio successfully created.\")\n",
    "\n",
    "position_set = PositionSet.from_list(\n",
    "    positions=['ARKK'],\n",
    "    date=dt.date(day=1, month=8, year=2022)\n",
    ")\n",
    "\n",
    "position_set.reference_notional = 1000000\n",
    "position_set.resolve()\n",
    "\n",
    "pm = PortfolioManager(portfolio.id)\n",
    "pm.update_positions([position_set])\n",
    "print(f\"Uploaded positions to '{portfolio.name}'.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Step 2: Configure risk engines to run three different factor models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "trading_model_ids = ['AXIOMA_AXUS5T', 'BARRA_USFAST', 'WOLFE_QES_US_AC_2']\n",
    "\n",
    "for model_id in trading_model_ids:\n",
    "    risk_report = FactorRiskReport(\n",
    "        report_type=ReportType.Portfolio_Factor_Risk,\n",
    "        position_source_type=PositionSourceType.Portfolio,\n",
    "        risk_model_id=model_id,\n",
    "        position_source_id=portfolio.id\n",
    "    )\n",
    "    risk_report.save()\n",
    "    print(f'Calculating risk with {model_id}...')\n",
    "\n",
    "pm.schedule_reports()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3 : Get factor risk and attribution results from GS Financial Cloud"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "pm = PortfolioManager('MP1B4W92HSFZRTKT') # replace with portfolio for the UI part of the demo\n",
    "risk_report = pm.get_factor_risk_report('BARRA_USFAST')\n",
    "attr_data = risk_report.get_factor_exposure(\n",
    "    start_date=risk_report.earliest_start_date,\n",
    "    end_date=risk_report.latest_end_date,\n",
    "    factor_names=['Beta', 'Value', 'Liquidity', 'Prospect', 'Downside Risk', 'Short Interest',\n",
    "                  'Size', 'Momentum', 'Sentiment', 'Growth', 'Seasonality', 'Long-Term Reversal']\n",
    ")\n",
    "for col in attr_data.columns:\n",
    "    if col != 'Date':\n",
    "        attr_data[col] = attr_data[col].div(1000000).round(2)\n",
    "\n",
    "pd.options.display.float_format = '$ {:,.2f} MM'.format\n",
    "\n",
    "display(attr_data)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(30, 20))\n",
    "ax = fig.add_subplot(projection='3d')\n",
    "colors = sns.color_palette(\"Spectral\", 12)\n",
    "\n",
    "attr_data = attr_data[[col for col in attr_data.columns.tolist() if col not in ['Date', 'Specific', 'Market', 'Industry', 'Style', 'Total', 'Factor']]]\n",
    "attr_data = attr_data.sort_values(by=0, axis=1, ascending=False)\n",
    "\n",
    "for index, row in attr_data.iterrows():\n",
    "    ax.bar(attr_data.columns.tolist(), row.to_numpy(), zs=attr_data.shape[0]-index, zdir='y', color=colors, alpha=1, width=1)\n",
    "\n",
    "ax.set_xticklabels(attr_data.columns.tolist(), rotation=47, ha='right')\n",
    "plt.yticks(np.arange(0, attr_data.shape[0], attr_data.shape[0]/12))\n",
    "ax.set_yticklabels(['Jan 2023', 'Dec', 'Nov', 'Oct', 'Sept', 'Aug', 'Jul', 'Jun', 'May', 'Apr', 'Mar', 'Feb 2022'], rotation=-24, ha='left')\n",
    "ax.set_zlabel('Exposure (Millions)')\n",
    "\n",
    "plt.show()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}